<template>
	<view class="container" :style="[containHeight]">
		<view class="search-content">
			<view class="search-item">
				<text class="search-label">题库标题：</text>
				<u--input placeholder="请输入查询的题库标题" border="surround" v-model="searchParams.bankName"></u--input>
			</view>
			<view class="btn-group">
				<u-button text="查询" type="primary" :loading="btnSearch" loadingText="查询中" class="search-btn"
					@click="toSearch"></u-button>
			</view>
		</view>
		<view class="content">
			<view class="delItem layout-start">
				<u-button text="创建题库" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)"
					@click="newBank()"></u-button>
			</view>
			<view v-if="bankList.length==0">
				<u-empty mode="list" icon="../../static/listEmpty.png"></u-empty>
			</view>
			<u-swipe-action v-for="(item,index) in bankList" :key="index" autoClose v-else>
				<u-swipe-action-item :options="optionsBank" :name="index" @click="swipeItem(item,$event)">
					<view class="historicalAchievements_item u-border-bottom">
						<text class="bold">题库名称：</text>
						<text>{{item.bankName}}</text>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
		</view>
		<u-modal :show="isNewEdit" :title="formTitle == 0 ? '创建题库' : '编辑题库'" showCancelButton @confirm="confirmBank"
			@cancel="cancelBank">
			<view class="popupContent layout-start">
				<text class="search-label">题库名称：</text>
				<u--input placeholder="请输入题库名称" border="surround" v-model="formDialog.bankName"></u--input>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		questionbankMain,
		queryBankName,
		deleteBankName,
		createBankName,
		updateBankName,
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				fullHeight: true,
				bankList: [],
				searchParams: {
					bankName: '',
				},
				btnSearch: false,
				optionsBank: [{
					text: '重命名',
					style: {
						backgroundColor: '#3c9cff'
					}
				}, {
					text: '编辑题目',
					style: {
						backgroundColor: '#3c9cff'
					}
				}, {
					text: '导出',
					style: {
						backgroundColor: '#3c9cff'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				isNewEdit: false,
				formTitle: 0, // 0-创建/1-编辑
				formDialog: {
					bankName: "",
				},
			}
		},
		onLoad() {
			this.userId = uni.getStorageSync('userinfo').id
			this.getbankList()
		},
		computed: {
			containHeight() {
				return this.fullHeight ? {
					/*#ifdef MP-WEIXIN*/
					// 微信小程序特有代码
					height: '100vh',
					/*#endif*/
					/*#ifndef MP-WEIXIN*/
					height: 'calc(100vh - 44px)'
					/*#endif*/
				} : {
					height: '100%'
				}
			},
		},
		onReachBottom() {
			if (this.fullHeight) {
				this.fullHeight = false
				console.log("onReachbottom");
			}
		},
		// onShow() {
		// 	this.fullHeight = true
		// },
		methods: {
			getbankList() {
				questionbankMain().then(s => {
					if (s.code === 20000) {
						this.bankList = s.data
						// this.$forceUpdate()
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			toSearch() {
				this.bankList = []
				queryBankName({
					bankName: this.searchParams.bankName
				}).then(s => {
					if (s.code === 20000) {
						this.bankList = s.data
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			swipeItem(item, e) {
				console.log("swipeItem e", e);
				console.log("item", item);
				if (e.index == 0) {
					//重命名
					this.isNewEdit = true
					this.formTitle = 1
					this.formDialog = item
				} else if (e.index == 1) {
					//编辑题目
					uni.navigateTo({
						url: `/pages/intensiveTraining/editBank?questionBankId=${item.id}`
					})

				} else if (e.index == 2) {
					//导出
					this.importBank(item)
				} else if (e.index == 3) {
					//删除
					let that = this
					uni.showModal({
						title: '提示',
						content: '此操作将永久删除该题库, 是否继续?',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								deleteBankName({
									id: item.id
								}).then(s => {
									if (s.code === 20000) {
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										})
										// this.$refs['swipeAction' + e.name][0].closeHandler();
										that.getbankList()
									} else {
										uni.showToast({
											title: s.message,
											icon: 'none'
										})
									}
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {

				}
			},
			newBank() {
				this.isNewEdit = true
				this.formTitle = 0;				
			},
			confirmBank() {
				this.isNewEdit = false
				if (this.formTitle == 0) {
					//创建
					createBankName({
						bankName: this.formDialog.bankName
					}).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '创建成功',
								icon: 'success'
							})
							this.getbankList()
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				} else if (this.formTitle == 1) {
					//重命名
					updateBankName({
						id: this.formDialog.id,
						bankName: this.formDialog.bankName
					}).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				}
			},
			importBank(item) {
				// #ifdef H5
				const getBaseUrl =  uni.getStorageSync('netVal');
				uni.request({
					url: getBaseUrl+'/jqmk/questionbank/exportQuestionBank',
					method: 'get',
					responseType: 'arraybuffer',
					header: {
						token: uni.getStorageSync('token'),
						"Content-type": "application/json; charset=UTF-8"
					},
					data: {
						questionBankId: item.id,
					},
					success: res => {
						if (res.statusCode === 200) {
							console.log("uni.request res", res);
							let blob = new Blob([res.data]);
							let downloadElement = document.createElement("a");
							let href = window.URL.createObjectURL(blob); //创建下载的链接
							downloadElement.href = href;
							downloadElement.download = `${item.bankName}.xlsx`; //下载后文件名
							document.body.appendChild(downloadElement);
							downloadElement.click(); //点击下载
							document.body.removeChild(downloadElement); //下载完成移除元素
							window.URL.revokeObjectURL(href); //释放掉blob对象
							//uni-app中Blob显示未被定义，在h5是没问题的，请问在App端如何解决这个问题？非H5端不是浏览器环境不支持 Dom、Bom 接口，没有 Blob 也没有 document 。

						}
					},
					fail: err => {}
				})
				// #endif

				// #ifdef APP
				const getBaseUrl =  uni.getStorageSync('netVal');
				uni.downloadFile({
					url: `${getBaseUrl}/jqmk/questionbank/exportQuestionBank?questionBankId=${item.id}`,
					header: {
						token: uni.getStorageSync('token'),
					},
					success: (res) => {
						const filePath = res.tempFilePath;
						if (res.statusCode === 200) {
							console.log('下载成功', res);
						}
						uni.saveFile({
							tempFilePath: filePath,
							success: (res1) => {
								// this.isShowProgress = false;
								console.log("uni.saveFile res1", res1);
								var saveFilePath = res1.savedFilePath;
								uni.showModal({
									title: "提示",
									content: "文件已保存：" + saveFilePath,
									cancelText: "我知道了",
									confirmText: "打开文件",
									success: (res2) => {
										if (res2.confirm) {
											uni.openDocument({
												filePath: saveFilePath,
												success: (res) => {
													console.log("打开文档成功",
														JSON.stringify(
															res))
												}
											})
										}
									}
								})
							}
						})
					},
				});
				// #endif
			},
			cancelBank(){
				this.isNewEdit=false
				this.formDialog={}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: linear-gradient(#5191FF 5%, #6AA2FF 8%, #BDD7FE 15%, #F6FAFF 100%);
		padding: 30rpx 30rpx;
		width: 100%;
		position: relative;
		box-sizing: border-box;
	}

	.content {
		background: #ffffff;
		margin-top: 30rpx;
		padding: 30rpx 32rpx;
		box-sizing: border-box;
		border-radius: 15rpx;
		opacity: 0.9;
		width: 100%;
		position: relative;
	}


	.historicalAchievements_item {
		background: #ffffff;
		box-sizing: border-box;
		padding: 30rpx;
		// border-radius: 20rpx;
		// box-shadow: 4px 4px 10px #888888;
	}

	.line {
		height: 1rpx;
		background: #737375;
		width: 100%;
		margin: 30rpx 0rpx;
	}


	.search-content {
		box-sizing: border-box;
		padding: 15rpx;
		width: 100%;
		position: relative;
		background: #ffffff;
		border-radius: 15rpx;
	}

	.search-label {
		max-width: 300rpx;
		overflow: hidden;
		// text-overflow: ellipsis;
		white-space: nowrap;
		font-size: 30rpx;
	}

	.search-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		margin-top: 10rpx;
		font-size: 30rpx;
		box-sizing: border-box;
		padding: 10rpx 20rpx;

	}

	.btn-group {
		display: flex;
		margin-top: 60rpx;
		width: 100%;
		position: relative;
		justify-content: space-between;
	}

	.search-btn {
		width: 40%;
		border-radius: 100rpx;
		background: linear-gradient(to right, #7774ff, #017ffd, #01b1fd);
		color: #fff;
	}

	.bold {
		font-weight: 700;
		white-space: nowrap;
	}

	.delItem {
		width: 30%;
		padding-top: 20rpx;
		box-sizing: border-box;
		position: relative;
		margin-bottom: 20rpx;
	}

	.popupContent {
		margin-top: 20rpx;
	}

	/deep/.u-swipe-action-item__right {
		position: absolute;
		top: 1px;
		bottom: 1px;
		right: 1px;
	}
</style>